/**
 * 
 */
package com.java.test.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.java.test.service.impl.ImportServiceImpl;
import com.java.test.util.FtpJSch;
import com.java.test.util.HttpErrorCode;
import com.java.test.util.JsonResult;

/**
 * @ 文件上传 --- ftp多种方式
 *
 */

@RestController
@RequestMapping("/file")
public class FileUploadController extends BaseController {

	@Autowired
	ImportServiceImpl importService;

	@Autowired
	FtpJSch ftpjsch;

	@RequestMapping("/upload")
	public JsonResult upload(@RequestBody MultipartFile file, HttpServletRequest request) {
		// 获取文件在服务器的储存位置
		JsonResult js = new JsonResult(HttpErrorCode.REQUESTSUCCESS.getCode(),
				HttpErrorCode.REQUESTSUCCESS.getContent());
		String path = request.getSession().getServletContext().getRealPath("/upload");
		File filePath = new File(path);

		System.out.println("文件的保存路径：" + path);
		if (!filePath.exists() && !filePath.isDirectory()) {
			System.out.println("目录不存在，创建目录:" + filePath);
			filePath.mkdir();
		}

		// 获取原始文件名称(包含格式)
		String originalFileName = file.getOriginalFilename();
		System.out.println("原始文件名称：" + originalFileName);

		// 获取文件类型，以最后一个`.`为标识
		String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
		System.out.println("文件类型：" + type);
		// 获取文件名称（不包含格式）
		String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

		// 设置文件新名称: 当前时间+文件名称（不包含格式）
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf.format(d);
		String fileName = date + name + "." + type;
		System.out.println("新文件名称：" + fileName);

		// 在指定路径下创建一个文件
		File targetFile = new File(path, fileName);

		// 将文件保存到服务器指定位置
		String showfileName="";
		try {
			file.transferTo(targetFile);
			ftpjsch.getConnect();
			showfileName =ftpjsch.upload(targetFile);
			ftpjsch.exitFtp();
			System.out.println("上传成功");
			// 将文件在服务器的存储路径返回
			// return new Result(true,"/upload/" + fileName);
		} catch (IOException e) {
			System.out.println("上传失败");
			e.printStackTrace();
			// return new Result(false, "上传失败");
		}

		js.setData(showfileName);
		return js;

	}

	@RequestMapping(value = "/excelupload")
	public String uploadExcel(HttpServletRequest request) throws Exception {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		MultipartFile file = multipartRequest.getFile("filename");
		if (file.isEmpty()) {
			return "文件不能为空";
		}
		InputStream inputStream = file.getInputStream();
		@SuppressWarnings("unchecked")
		List<List<Object>> list = importService.getBankListByExcel(inputStream, file.getOriginalFilename());
		inputStream.close();

		for (int i = 0; i < list.size(); i++) {
			List<Object> lo = list.get(i);
			// TODO 随意发挥
			System.out.println(lo);
		}
		return "上传成功";
	}

	/**
	 * 描述：下载导入用户模板
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "downloadexcelTemp")
	public void downloadTemp(HttpServletResponse response, HttpServletRequest request) {

		InputStream inputStream = null;
		OutputStream out = null;

		try {
			ClassPathResource classPathResource = new ClassPathResource("static/excel/template.xlsx");
			inputStream = classPathResource.getInputStream();
			response.setContentType("application/octet-stream");
			out = response.getOutputStream();
			response.setHeader("Content-Disposition", "attachment; filename=template.xlsx");
			int b = 0;
			byte[] buffer = new byte[1024 * 1024];
			while (b != -1) {
				b = inputStream.read(buffer);
				if (b != -1)
					out.write(buffer, 0, b);
			}
			inputStream.close();
			out.close();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("downloadExcel error!");
		}

	}

}
